package com.amumu.drama.common.modules.delivery.config;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.amumu.drama.common.constant.DeliveryProviderEnum;
import com.amumu.drama.common.constant.OrderTypeEnum;
import com.amumu.drama.common.exception.Asserts;
import com.amumu.drama.common.modules.delivery.handler.DeliveryHandler;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * @author sunzhuang
 * @date 2024/6/27 15:00
 * @slogan 天下风云出我辈, 一入代码岁月催
 * @desc todo
 */

@Slf4j
@Component
public class DeliveryConfig implements ApplicationContextAware {


    /*** 发货处理器 */
    public static Map<String, DeliveryHandler> DELIVERY_HANDLER_MAP = Maps.newHashMap();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, DeliveryHandler> deliveryHandlerMap = applicationContext.getBeansOfType(DeliveryHandler.class);
        for (DeliveryHandler deliveryHandler : deliveryHandlerMap.values()) {
            List<String> typeList = deliveryHandler.type();
            if (CollUtil.isEmpty(typeList)) {
                log.error("初始化发货处理器失败，type为空，claseName:{}", deliveryHandler.getClass());
                Asserts.fail("初始化发货处理器失败，type为空");
            }
            for (String type : typeList) {
                DELIVERY_HANDLER_MAP.put(type, deliveryHandler);
            }
        }
    }

    public static DeliveryHandler getDeliveryHandler(OrderTypeEnum orderTypeEnum, DeliveryProviderEnum deliveryProviderEnum) {
        return DELIVERY_HANDLER_MAP.get(getDeliveryType(orderTypeEnum, deliveryProviderEnum));
    }

    public static DeliveryHandler getDeliveryHandler(Integer orderType, String deliveryProvider) {
        OrderTypeEnum orderTypeEnum = OrderTypeEnum.getByCode(orderType);
        DeliveryProviderEnum deliveryProviderEnum = DeliveryProviderEnum.getByCode(deliveryProvider);
        return DELIVERY_HANDLER_MAP.get(getDeliveryType(orderTypeEnum, deliveryProviderEnum));
    }

    public static String getDeliveryType(OrderTypeEnum orderTypeEnum, DeliveryProviderEnum deliveryProviderEnum) {
        return StrUtil.join("_", orderTypeEnum.getCode(), deliveryProviderEnum.getCode());
    }

    public static DeliveryHandler getDeliveryHandlerByType(String deliveryType) {
        return DELIVERY_HANDLER_MAP.get(deliveryType);
    }

}
